package com.nectech.util;

import com.nectech.constant.Constant;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;

/**
 * @Author: 浅小北
 * @ClassName: MusicThread
 * @Description:
 * @Date: 2021/2/1 20:34
 * @Since: version-1.0
 */
public class MusicThread extends Thread{
    /**
     * 播放器类
     */
    private Player player;
    /**
     * mp3文件的路径（相对路径）
     */
    private String musicPath;
    /**
     * 是否循环
     */
    private boolean loop;
    public MusicThread() {

    }
    /**
     *
     * @param musicName MP3文件的相对路径
     */
    public MusicThread(String musicName) {
        this.musicPath = Constant.PRE_MP3 + musicName;
    }
    /**
     *
     * @param musicName MP3文件的相对路径
     * @param loop 是否循环
     */
    public MusicThread(String musicName,boolean loop) {
        this.musicPath = Constant.PRE_MP3 + musicName;
        this.loop = loop;
    }

    @Override
    public void run() {
        try {
            if(loop) {
                while(true) {
                    play();
                }
            }else {
                play();
            }
        } catch (FileNotFoundException | JavaLayerException e) {
            e.printStackTrace();
        }
    }
    private void play() throws FileNotFoundException, JavaLayerException{
        BufferedInputStream buffer = new BufferedInputStream(MusicThread.class.getClassLoader().getResourceAsStream(musicPath));
        // 创建播放器类
        player = new Player(buffer);
        // 播放
        player.play();
    }

    /*public static void main(String[] args) {
        new MusicThread("bgmusic/AcientForest.mp3", true).start();
    }*/
}
